package com.example.dbcenter.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.dbcenter.conf.DbLogger;
import com.example.dbcenter.conf.ReflectUtil;
import com.example.dbcenter.dbase.DbHelper;
import com.example.dbcenter.intf.DbOperations;
import com.example.dbcenter.conf.excutor.DbExcutor.DBTYPE;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DbOperationImpl extends DbHelper implements DbOperations {
    private SqlSessionTemplate sqlSessionTemplate;
    private final int lostAffect;
    private DBTYPE dbType;
    private String chartset;
    private final String SQL_SELECT;
    private final String SQL_INSERT;
    private final String SQL_UPDATE;
    private final String SQL_DELETE;
    private DbLogger logger;
    private ExecutorType executorType;

    public DbOperationImpl(SqlSessionFactory sqlSessionFactory, int lostAffect) {
        this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType(), (String)null);
    }
    public DbOperationImpl(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, String characterSet) {
        this.lostAffect = -2147482646;
        this.dbType = DBTYPE.MYSQL;
        this.chartset = null;
        this.SQL_SELECT = "mybatis.sql.select";
        this.SQL_INSERT = "mybatis.sql.insert";
        this.SQL_UPDATE = "mybatis.sql.update";
        this.SQL_DELETE = "mybatis.sql.delete";
        this.logger = new DbLogger();
        this.executorType = executorType;
        this.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.SIMPLE);
        this.dbType = this.getDBType();
        this.chartset = characterSet;
    }

    /*
        1，支持mysql
     */
    public DBTYPE getDBType() {
        String type = "";
        DataSource dataSource = this.sqlSessionTemplate.getConfiguration().getEnvironment().getDataSource();
        if (dataSource instanceof DruidDataSource) {
            type = ((String) ReflectUtil.getFieldValue(dataSource, "jdbcUrl")).toLowerCase();
        } else {
            type = ((String)ReflectUtil.getFieldValue(dataSource, "url")).toLowerCase();
        }
        if(type.indexOf("${")> -1) {
            type = getEnvValue(type);
        }
        int first = type.indexOf(":");
        type = type.substring(first + 1, type.indexOf(":", first + 1));
        return DBTYPE.MYSQL;

//        if ("mysql".equalsIgnoreCase(type)) {
//            return DBTYPE.MYSQL;
//        } else {
//            return "sysbase".equalsIgnoreCase(type) ? DBTYPE.SQLITE : DBTYPE.OTHERSQL;
//        }

    }
    public static String getEnvValue(String keySource) {
        String keyData = keySource.toString();

        int startPos = keyData.indexOf("${");
        System.out.println("debug-xys: startPos"+startPos);
        if (startPos >= 0) {
            final Pattern pattern = Pattern.compile("(\\$\\{[^>]*?\\})");
            StringBuffer buffer = new StringBuffer();

            System.out.println("debug-xys: keyData"+keyData);
            Matcher matcher = pattern.matcher(keyData);
            while (matcher.find()) {
                String findKey = matcher.group();
                String dataKey = findKey.replaceAll("\\$\\{", "").replaceAll("\\}", "");
                // 获取环境变量
                System.out.println("debug-xys: datakey"+dataKey);
                //String dataNew = env.getProperty(dataKey);
                String dataNew = System.getenv(dataKey);
                System.out.println("debug-xys: dataNew"+dataNew);
                if (!StringUtils.isEmpty(dataNew)) {
                    matcher.appendReplacement(buffer, dataNew.toString());
                }
            }
            matcher.appendTail(buffer);
            return buffer.toString();
        }

        return keySource;
    }
    @Override
    public void insert(Object obj) {
        insert(obj,fetchAnnotationTableName(obj.getClass()));
    }

    @Override
    public void insert(Collection<?> collection, Class<?> clazz) {

    }

    @Override
    public void insert(Object obj, String str) {

    }



    @Override
    public void insert(Collection<?> collection, String str) {

    }

    @Override
    public void insertAll(Collection<?> collection) {

    }

    @Override
    public int delete(Object obj) {
        return 0;
    }

    @Override
    public int delete(Object obj, String str) {
        return 0;
    }

    @Override
    public int delete(Query query, Class<?> clazz) {
        return 0;
    }

    @Override
    public int delete(Query query, Class<?> clazz, String str) {
        return 0;
    }

    @Override
    public int delete(Query query, String str) {
        return 0;
    }

    @Override
    public int updateOrInsert(Query query, Update upt, Class<?> clazz) {
        return 0;
    }

    @Override
    public int updateOrInsert(Query query, Update upt, String str) {
        return 0;
    }

    @Override
    public int updateOrInsert(Query query, Update upt, Class<?> clazz, String str) {
        return 0;
    }

    @Override
    public int update(Query query, Update upt, Class<?> clazz) {
        return 0;
    }

    @Override
    public int update(Query query, Update upt, String str) {
        return 0;
    }

    @Override
    public int update(Query query, Update upt, Class<?> clazz, String str) {
        return 0;
    }

    @Override
    public <T> T selectOne(Query query, Class<T> tClass) {
        return null;
    }

    @Override
    public <T> T selectOne(Query query, Class<T> tClass, String str) {
        return null;
    }

    @Override
    public Map<String, Object> selectOne(Query query, String str) {
        return null;
    }

    @Override
    public <T> List<T> select(Query query, Class<T> tClass) {
        return null;
    }

    @Override
    public <T> List<T> select(Query query, Class<T> tClass, String str) {
        return null;
    }

    @Override
    public List<Map<String, Object>> select(Query query, String str) {
        return null;
    }

    @Override
    public long count(Query query, Class<?> clazz) {
        return 0;
    }

    @Override
    public long count(Query query, String str) {
        return 0;
    }

    @Override
    public void destroy() {

    }
}
